<!doctype html>
<title>A hidden carret should not receive ClipboardEvent</title>
<link rel="help" href="https://www.w3.org/TR/clipboard-apis/#fire-a-clipboard-event">
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>

<input type="checkbox" id="checkbox">
<textarea id="textcontrol">HEY</textarea>

<script>
// We use testRunner.execCommand() to test user-triggered (not scripted) clipboard events.
testClipboardEvent = function(eventName, selectedElement) {
  let selectionHitCount = 0;
  let documentHitCount = 0;
  let lastTarget;
  selectionLog = function(e) {
    selectionHitCount++;
    lastTarget = e.target;
  }
  documentLog = function(e) {
    documentHitCount++;
    lastTarget = e.target;
  }
  selectedElement.addEventListener(eventName, selectionLog);
  document.addEventListener(eventName, documentLog);

  selectedElement.focus();
  testRunner.execCommand(eventName);
  assert_equals(selectionHitCount, 1, `The <textarea> should receive one ${eventName}-event.`)
  assert_equals(documentHitCount, 1, `The document should receive one bubbled ${eventName}-event.`)
  assert_equals(lastTarget, selectedElement, `The <textarea> should be the ${eventName}-event's target.`)

  checkbox.focus();
  testRunner.execCommand(eventName);
  assert_equals(selectionHitCount, 1, `The carret is hidden in the <textarea> so the <textarea> should not receive an ${eventName}-event.`)
  assert_equals(documentHitCount, 2, `The document should receive one ${eventName}-event.`)
  assert_equals(lastTarget, document.body, `The document should be the ${eventName}-event's target.`)

  checkbox.blur();
  testRunner.execCommand(eventName);
  assert_equals(selectionHitCount, 1, `The carret is hidden in the <textarea> so the <textarea> should not receive an ${eventName}-event.`)
  assert_equals(documentHitCount, 3, `The document should receive one ${eventName}-event.`)
  assert_equals(lastTarget, document.body, `The document should be the ${eventName}-event's target.`)

  document.body.focus();
  testRunner.execCommand(eventName);
  assert_equals(selectionHitCount, 1, `The carret is hidden in the <textarea> so the <textarea> should not receive an ${eventName}-event.`)
  assert_equals(documentHitCount, 4, `The document should receive another ${eventName}-event.`)
  assert_equals(lastTarget, document.body, `The document should be the ${eventName}-event's target.`)
}

test(() => testClipboardEvent('copy', textcontrol),  'Hidden carrets in textcontrols are not targeted by copy-events.');
test(() => testClipboardEvent('paste', textcontrol), 'Hidden carrets in textcontrols are not targeted by paste-events.');
test(() => testClipboardEvent('cut', textcontrol),   'Hidden carrets in textcontrols are not targeted by cut-events.');
</script>
